package com.android.scanner.fragment;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.android.scanner.R;
import com.android.scanner.adapter.CommonAdapter;
import com.android.scanner.bean.ProjectBean;
import com.android.scanner.utils.ComparatorUtil;
import com.android.scanner.utils.Constant;
import com.android.scanner.utils.LoadingUtil;
import com.android.scanner.utils.PreferencesUtil;
import com.android.scanner.utils.SoapUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class CenterFragment extends BaseFragment implements OnClickListener,
		OnItemSelectedListener, OnItemClickListener {
	private Handler handler;
	private Context context;
	private List<ProjectBean> list = null;
	private CommonAdapter adapter = null;
	private ListView lv;
	private Button btnLeft, btnMiddle, btnRight;
	private TextView tvPara;
	private int curPosition = 0;
	private int orderType = 0;
	private static CenterFragment mSelft = null;

	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == Constant.MSG_GET_PROJECTS) {
				list = (List<ProjectBean>) msg.obj;
				if (list != null && list.size() > 0) {
					Gson gson = new Gson();
					String json = gson.toJson(list);
					PreferencesUtil.setStringPref(context,
							PreferencesUtil.NAME_WORKLIST, json);
					Log.i("kirk", "kirk add - json is " + json);

					showData();
				}

				LoadingUtil.hide();
			}
		};
	};

	public static CenterFragment getInstance(Handler handler) {
		if (mSelft != null)
			return mSelft;
		return new CenterFragment(handler);
	}

	public CenterFragment(Handler handler) {
		this.handler = handler;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		context = getActivity();
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.fragment_center, null);
		initViews(view);
		initData();
		return view;
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		// if (adapter != null) {
		// Log.e("kirk", "kirk add - curPosition is " + curPosition);
		// lv.setSelection(curPosition);
		// adapter.updateHLPosition(curPosition);
		// }
		super.onResume();
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	public void initData() {
		orderType = PreferencesUtil.getIntPref(context,
				PreferencesUtil.NAME_ORDER, 0);

		String json = PreferencesUtil.getStringPref(context,
				PreferencesUtil.NAME_WORKLIST, "");
		if (!json.equals("")) {
			showData();
			return;
		}

		LoadingUtil.show(context);

		Map map = new LinkedHashMap<String, String>();
		map.put("method", SoapUtil.METHOD_GETPROJECTS);
		map.put("action", SoapUtil.ACTION_GETPROJECTS);
		map.put("organizationId", "1f163ed1-ff3e-4034-844b-21539552900f");

		SoapUtil.runMethod(map, mHandler);
	}

	private void initViews(View view) {
		// TODO Auto-generated method stub

		tvPara = (TextView) view.findViewById(R.id.tv_para);
		btnLeft = (Button) view.findViewById(R.id.btn_left);
		btnMiddle = (Button) view.findViewById(R.id.btn_middle);
		btnRight = (Button) view.findViewById(R.id.btn_right);
		btnLeft.setOnClickListener(this);
		btnMiddle.setOnClickListener(this);
		btnRight.setOnClickListener(this);
		lv = (ListView) view.findViewById(R.id.lv);

		lv.requestFocus();
		lv.setSelection(curPosition);

		lv.setOnItemSelectedListener(this);
		lv.setOnItemClickListener(this);
	}

	private void showData() {
		String json = PreferencesUtil.getStringPref(context,
				PreferencesUtil.NAME_WORKLIST, "");
		if (!json.equals("")) {
			Type typeToken = new TypeToken<List<ProjectBean>>() {
			}.getType();
			Gson gson = new Gson();
			list = gson.fromJson(json, typeToken);
		} else {
			return;
		}

		ComparatorUtil comparator = new ComparatorUtil(orderType);
		Collections.sort(list, comparator);

		List<String> listString = new ArrayList<String>();

		for (int i = 1; i < list.size(); i++)
			listString.add(list.get(i).Name);

		adapter = new CommonAdapter(context, listString, lv, curPosition);
		lv.setAdapter(adapter);
		String str = String.format(
				context.getResources().getString(R.string.arg_value),
				list.size());
		tvPara.setText(str);
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		if (arg0.getId() == R.id.btn_left) {
			handler.sendEmptyMessage(Constant.MSG_MAIN_OPTION);
		} else if (arg0.getId() == R.id.btn_right) {
			handler.sendEmptyMessage(Constant.MSG_MAIN_NEWWORK);
		}
	}

	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
			long arg3) {
		// TODO Auto-generated method stub
		curPosition = arg2;
		adapter.updateHLPosition(curPosition);
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub
	}

	@Override
	public boolean setKeyEvent(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		// Toast.makeText(context, "key Event is " + keyCode,
		// Toast.LENGTH_SHORT)
		// .show();
		switch (keyCode) {
		case KeyEvent.KEYCODE_MENU:
			btnLeft.callOnClick();
			break;
		case KeyEvent.KEYCODE_BACK:
			btnRight.callOnClick();
			break;
		case KeyEvent.KEYCODE_F5:
			btnMiddle.callOnClick();
			break;
		case KeyEvent.KEYCODE_1:
		case KeyEvent.KEYCODE_2:
		case KeyEvent.KEYCODE_3:
		case KeyEvent.KEYCODE_4:
		case KeyEvent.KEYCODE_5:
		case KeyEvent.KEYCODE_6:
		case KeyEvent.KEYCODE_7:
		case KeyEvent.KEYCODE_8:
		case KeyEvent.KEYCODE_9:
			lv.setSelection(keyCode - 8);
			clickItem(keyCode - 8);
			break;

		}
		// if (keyCode == KeyEvent.KEYCODE_MENU) {
		// btnLeft.callOnClick();
		// } else if (keyCode == KeyEvent.KEYCODE_BACK) {
		// btnRight.callOnClick();
		// } else if (keyCode == KeyEvent.KEYCODE_F5) {
		// btnMiddle.callOnClick();
		// } else if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
		// Message msg = new Message();
		// msg.arg1 = lv.getSelectedItemPosition();
		// msg.what = Constant.BB_LIST;
		// handler.sendMessage(msg);
		// }
		return super.setKeyEvent(keyCode, event);
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		clickItem(arg2);
	}

	public void clickItem(int position) {
		if (position > list.size())
			return;

		Message msg = new Message();
		msg.arg1 = lv.getSelectedItemPosition();
		msg.what = Constant.BB_LIST;
		handler.sendMessage(msg);
	}

}
